<template>
	<div class="main" :style="{ zoom: zoom }">
		<div class="jngbox">
			<div class="mubj" ref="memorialArea">
				<div class="mubei"></div>
			</div>
			<div class="beiwen" style="width: 140px; height: 260px; left: 886px; top: 323px;">
				<!-- <div class="beiphoto"><img src="/uptupian/pc18/t2019221192315.JPG" border="0"></div> -->
				<div class="beitext"><span class="nametext name1">郑然</span><span class="zhimu">之<br>墓</span></div>
			</div>

			<!-- <div class="box box-4" id="jpboxmain">
				<div class="t-shade"></div>
				<div class="t-content"></div>

			</div> -->
			<!-- 祭品区域 -->
			<!-- <div class="offerings-area"> -->
				<!-- 祭品台 -->
				<!-- 可拖动的祭品 -->
				<!-- <div v-for="offering in offerings" :key="offering.id" class="offering-item"
					:class="{ 'dragging': isDragging && draggedOffering?.id === offering.id }"
					:style="getOfferingPosition(offering)" @mousedown="startDrag($event, offering, false)"
					@touchstart="startDrag($event, offering, true)">
					<img src="@/assets/images/flower1.png">
				</div>
			</div> -->
		</div>
		<!-- 左侧导航 -->
		<div class="side-nav">
			<div v-for="(item, index) in navItems" :key="index" class="nav-item" @click="handleNavClick(item)">
				{{ item.name }}
			</div>
		</div>
		

		<!-- 底部操作栏 -->
		<div class="bottom-actions">
			<div class="action-button" @click="showOfferingDialog(item.name)" v-for="item in giftCateList" :key="item.id">
				<!-- <i class="icon-flower"></i> -->
				{{ item.name }}
			</div>
		</div>
		<!-- 祭品选择弹窗 -->
		<!-- <el-dialog v-model="offeringDialogVisible" :title="dialogTitle" width="50%" class="offering-dialog">
			<div class="offering-list">
				<div v-for="item in currentOfferingItems" :key="item.id" class="offering-option"
					@click="selectOffering(item)">
					<img src="@/assets/images/flower1.png">
					<div class="offering-info">
						<div class="name">{{ item.name }}</div>
						<div class="price">{{ item.price }}永恒币</div>
					</div>
				</div>
			</div>
		</el-dialog> -->
		<!-- <gift-popup ref="giftPopupRef" v-if="showEdit" @success="selectOffering" @close="showEdit = false"></gift-popup> -->

		 <!-- 放置我们的组件 -->
		 <MemorialPlacement ref="memorialPlacementRef" @placement-confirmed="handlePlacement" @placement-cancelled="handleCancel" :giftCateList="giftCateList"/>
		<!-- 显示已放置的物品 (示例) -->
		<div v-for="item in placedItems" :key="item.id" :style="item.style" class="placed-item-display">
			<img :src="item.image" :alt="item.name">
			<!-- 可以显示寄语等 -->
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick, shallowRef } from 'vue'
import type { Ref } from 'vue'
import { apiMuGiftCate, apiMuGiftList, apiMuGiftAdd } from '@/api/gift'
import { apiMuDetail } from '@/api/graveyard'
import GiftPopup from './giftPopup.vue'
import type { CSSProperties } from 'vue';
import { useRoute } from 'vue-router'
const route = useRoute()

// 測試 =============================================================================================================================================================================
import MemorialPlacement from './MemorialPlacement.vue'; // 假设放在 components 目录下

const memorialPlacementRef = shallowRef<InstanceType<typeof MemorialPlacement>>()
interface PlacedItem {
    id: string; // 需要唯一ID
    name: string;
    image?: string;
    style: CSSProperties;
    message?: string;
}

const placedItems = ref<PlacedItem[]>([]);

// 处理放置确认事件
const handlePlacement = async (data: { item: any; position: { x: number; y: number; }; message: string; paymentMethod: string }) => {
  console.log('父组件收到确认:', data);

  // 在这里，你可以将最终确认的物品及其位置信息添加到你的场景中
  // 例如，将数据保存到列表，然后在模板中渲染出来
  const newItem: PlacedItem = {
      id: `${data.item.id}-${Date.now()}`, // 创建一个唯一ID
      name: data.item.name,
      image: data.item.cover,
      style: {
          position: 'absolute',
          left: `${data.position.x}px`,
          top: `${data.position.y}px`,
          zIndex: 10, // 确保在背景之上，低于交互组件
      },
      message: data.message
  }
  placedItems.value.push(newItem);

  await apiMuGiftAdd({mu_id: route.query.id, gift_id: data.item.id, position: `${data.position.x},${data.position.y}`})

  // ... 其他逻辑，如扣除费用等
};

// 处理放置取消事件
const handleCancel = () => {
  console.log('父组件收到取消');
  // 可以添加一些用户提示或逻辑
};





//  =============================================================================================================================================================================


// const giftPopupRef = shallowRef<InstanceType<typeof GiftPopup>>()
// const showEdit = ref(false)

// interface OfferingItem {
// 	id: number
// 	name: string
// 	image: string
// 	price: number
// 	type: string
// 	position?: {
// 		x: number
// 		y: number
// 	}
// }

interface NavItem {
	name: string
	key: string
}

// 导航项
const navItems = reactive<NavItem[]>([
	{ name: '生平', key: 'life' },
	{ name: '文章', key: 'articles' },
	{ name: '相册', key: 'photos' },
	{ name: '留言', key: 'messages' },
	{ name: '献歌', key: 'songs' },
	{ name: '视频', key: 'videos' },
	{ name: '转告', key: 'forward' }
])

// 纪念馆信息
// const memorialInfo = reactive({
// 	name: '张某某',
// 	id: '102309570'
// })

// 已放置的祭品
// const offerings = ref<OfferingItem[]>([])
// const draggableRefs = ref<(HTMLElement | null)[]>([])

// 祭品选择弹窗
// const offeringDialogVisible = ref(false)
// const currentOfferingType = ref('')

// 弹窗标题
// const dialogTitle = computed(() => {
// 	const titles: Record<string, string> = {
// 		flower: '献花',
// 		incense: '上香',
// 		candle: '点烛',
// 		offering: '祭品',
// 		decoration: '装饰',
// 		clean: '扫墓'
// 	}
// 	return titles[currentOfferingType.value] || '选择祭品'
// })

// 所有可选祭品列表
// const allOfferingItems = reactive<OfferingItem[]>([])

// // 当前类型的祭品列表
// const currentOfferingItems = computed(() => {
// 	return allOfferingItems.filter((item: OfferingItem) => item.type === currentOfferingType.value)
// })



// 数据
const giftCateList = ref([])
const giftList = ref([])
const getpiMuGiftList = async () => {
	let data = giftCateList.value.find(item => item.name == '献花') as any
	const res = await apiMuGiftList({cid: data.id})
	console.log(res)
	giftList.value = res
}
const getApiMuGiftCate = async () => {
	const res = await apiMuGiftCate()
	console.log(res)
	giftCateList.value = res.sort((a, b) => a.sort - b.sort)
}

// 获取详情
const getMuDetail = async () => {
	const res = await apiMuDetail({id: route.query.id})
	console.log(res)
}



// 显示祭品选择弹窗
const currentOfferingType = ref('')
const showOfferingDialog = async (type: string) => {
	console.log(type)
	currentOfferingType.value = type
	// offeringDialogVisible.value = true
	// showEdit.value = true
	memorialPlacementRef.value?.open()
	await nextTick()
	// giftPopupRef.value?.setFormData({
	// 	// mu_id: props.memorialId,
	// 	giftCateList: giftCateList.value,
	// 	giftList: giftList.value
	// })
	// giftPopupRef.value?.open('add')

}

// 选择祭品
// const selectOffering = (item: any) => {
// 	// 添加新的祭品到默认位置
// 	offerings.value.push({
// 		...item,
// 		position: {
// 			x: 50,
// 			y: 50
// 		}
// 	})
// 	// offeringDialogVisible.value = false
// }






























// 墓碑区域引用
// const memorialArea = ref<HTMLElement | null>(null)

// // 祭品拖动相关数据
// const draggedOffering = ref<OfferingItem | null>(null)
// const isDragging = ref(false)
// const startX = ref(0)
// const startY = ref(0)

// // 设置拖拽引用
// const setDraggableRef = (el: HTMLElement | null, index: number) => {
// 	if (el) {
// 		draggableRefs.value[index] = el
// 		el.draggable = true
// 		el.style.cursor = 'move'

// 		const offering = offerings.value[index]
// 		el.addEventListener('mousedown', (e: MouseEvent) => {
// 			startDrag(e, offering, false)
// 		})
// 	}
// }

// // 处理导航点击
// const handleNavClick = (item: NavItem) => {
// 	// 处理导航项点击...
// }



// // 开始拖动
// const startDrag = (event: MouseEvent | TouchEvent, offering: OfferingItem, isTouch: any) => {
// 	console.log('startDrag', event)
// 	// 阻止触摸事件的默认行为，但允许鼠标事件正常进行
// 	if (isTouch) {
// 		console.log('触摸事件')
// 		event.preventDefault()
// 	}

// 	draggedOffering.value = offering
// 	isDragging.value = true

// 	// 记录起始位置
// 	if ('clientX' in event) {
// 		startX.value = event.clientX
// 		startY.value = event.clientY
// 	} else if (event.touches && event.touches[0]) {
// 		startX.value = event.touches[0].clientX
// 		startY.value = event.touches[0].clientY
// 	}

// 	// 添加移动和结束事件监听器
// 	document.addEventListener('mousemove', handleDragMove)
// 	document.addEventListener('touchmove', handleDragMove, { passive: false })
// 	document.addEventListener('mouseup', endDrag)
// 	document.addEventListener('touchend', endDrag)
// }

// // 移动处理
// const handleDragMove = (event: MouseEvent | TouchEvent) => {
// 	if (!isDragging.value || !draggedOffering.value || !memorialArea.value) return

// 	// 只为触摸事件阻止默认行为
// 	if ('touches' in event) {
// 		event.preventDefault()
// 	}

// 	let clientX, clientY
// 	if ('clientX' in event) {
// 		clientX = event.clientX
// 		clientY = event.clientY
// 	} else if (event.touches && event.touches[0]) {
// 		clientX = event.touches[0].clientX
// 		clientY = event.touches[0].clientY
// 	} else {
// 		return // 无法确定位置，退出
// 	}

// 	const rect = memorialArea.value.getBoundingClientRect()
// 	const x = ((clientX - rect.left) / rect.width) * 100
// 	const y = ((clientY - rect.top) / rect.height) * 100

// 	// 确保位置在有效范围内
// 	if (draggedOffering.value.position) {
// 		draggedOffering.value.position = {
// 			x: Math.max(0, Math.min(100, x)),
// 			y: Math.max(0, Math.min(100, y))
// 		}
// 	}
// }

// // 结束拖动
// const endDrag = () => {
// 	if (isDragging.value && draggedOffering.value) {
// 		console.log('结束拖动', toRaw(draggedOffering.value))
// 		// 处理结束拖动，保存位置
// 		// updateOfferingPosition(draggedOffering.value)
// 	}

// 	// 重置状态并移除事件监听器
// 	isDragging.value = false
// 	draggedOffering.value = null
// 	document.removeEventListener('mousemove', handleDragMove)
// 	document.removeEventListener('touchmove', handleDragMove)
// 	document.removeEventListener('mouseup', endDrag)
// 	document.removeEventListener('touchend', endDrag)
// }

// // 获取祭品位置样式
// const getOfferingPosition = (offering: OfferingItem | any) => {
// 	if (!offering.position) return {}

// 	// 当正在拖动当前祭品时，提高z-index
// 	return {
// 		position: 'absolute',
// 		left: `${offering.position.x}%`,
// 		top: `${offering.position.y}%`,
// 		zIndex: isDragging.value && draggedOffering.value?.id === offering.id ? '10' : '1',
// 		// 移除可能在此处的transition，拖动时要禁用过渡效果
// 	}
// }

// // 更新祭品位置到后端
// const updateOfferingPosition = async (offering: OfferingItem) => {
// 	try {
// 		await fetch('/api/offerings/position', {
// 			method: 'POST',
// 			headers: {
// 				'Content-Type': 'application/json'
// 			},
// 			body: JSON.stringify({
// 				offeringId: offering.id,
// 				position: offering.position
// 			})
// 		})
// 	} catch (error) {
// 		console.error('更新位置失败:', error)
// 	}
// }
const zoom = ref(1)
onMounted(async () => {
	console.log(navigator.userAgent)
	console.log(window)
	const userAgent = navigator.userAgent
	const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
	if (isMobile) {
		zoom.value = 0.5
	}
	zoom.value = (window.innerWidth - 15) / 1920
	// fun()

	await getApiMuGiftCate()
	await getpiMuGiftList()
	await getMuDetail()
})

// const scrollbarWidth = ref(0)
// const fun = () => {
// 	// 创建一个临时div元素
// 	const outer = document.createElement('div');
// 	outer.style.visibility = 'hidden';
// 	outer.style.width = '100px'; // 或者任何固定宽度，确保有滚动条出现
// 	outer.style.height = '100px'; // 同上，确保有滚动条出现
// 	outer.style.overflow = 'scroll'; // 此元素必须有滚动条
// 	document.body.appendChild(outer);
// 	scrollbarWidth.value = outer.offsetWidth - outer.clientWidth; // 计算差值即为滚动条宽度
// 	document.body.removeChild(outer); // 清理临时元素
// 	console.log('scrollbarWidth==================================', scrollbarWidth.value, outer.offsetWidth, outer.clientWidth)
// }
</script>

<style scoped>
.main {
	width: 1920px;
	height: 1080px;
	margin: 0 auto;
	position: relative;
}

.jngbox {
	width: 1920px;
	height: 1080px;
	position: relative;
	overflow: hidden;
}

.mubj {
	background-image: url(../../assets/images/bj2.png);
	width: 1920px;
	height: 100%;
	min-height: 600px;
	top: 0;
	left: 0;
	z-index: 1;
	position: absolute;
	background-position: top center;
	background-size: 1920px auto;
	background-repeat: no-repeat;
}

.mubei {
	width: 1920px;
	height: 1080px;
	top: 0;
	left: 0;
	z-index: 2;
	background-position: bottom center;
	background-size: 1920px auto;
	background-repeat: no-repeat;
	background-image: url(../../assets/images/mudi1.png);
}

.beiwen {
	z-index: 5;
	position: absolute;
	overflow: hidden;
	background-position: bottom center;
	background-repeat: no-repeat;
}

.side-nav {
      position: fixed;
      /* _position: absolute; */
      font-size: 1.2rem;
      width: 70px;
      top: 200px;
      left: 0;
      z-index: 1004;
      background-color: rgba(0, 0, 0, 0.3);
      padding: 2px 5px 3px 5px;
      -moz-border-radius: 5px;
      -webkit-border-radius: 5px;
      border-radius: 5px;
  }
  
  .nav-item {
    color: white;
    padding: 15px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .nav-item:hover {
    background: rgba(0, 0, 0, 0.5);
    /* transform: translateX(5px); */
  }

  /* 底部操作栏 */
  .bottom-actions {
      position: fixed;
      width: 94%;
      min-width: 420px;
      max-width: 700px;
      padding: 8px 12px;
      left: 0;
      right: 0;
      margin: 0 auto;
      background: #000;
      bottom: 30px;
      z-index: 99999;
      background-color: rgba(0, 0, 0, 0.2);
      -moz-border-radius: 10px;
      -webkit-border-radius: 10px;
      border-radius: 10px;
      display: flex;
      justify-content: space-between;
  }
  
  .action-button {
    gap: 18px;
  	flex: 1;
    color: #fff;
	font-size: 1.4rem;
	text-decoration: none;
	background: #242424;
	height: 100%;
	padding: 5px;
	display: inline-block;
	line-height: 38px;
	text-align: center;
	border: #fddebf 1px solid;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px;
	margin: 5px;
  }
  
  .action-button:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  }
  
  .action-button i {
    font-size: 20px;
  }
  
  /* 弹窗样式 */
  .offering-dialog {
    :deep(.el-dialog) {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }
  
    .offering-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 20px;
      padding: 20px;
    }
  }
  
  .offering-option {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    background: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
    &:hover {
      transform: scale(1.05) translateY(-5px);
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    }
  
    img {
      width: 80px;
      height: 80px;
      object-fit: contain;
      margin-bottom: 10px;
    }
  
    .offering-info {
      .name {
        font-size: 16px;
        color: #333;
        margin-bottom: 5px;
      }
      
      .price {
        font-size: 14px;
        color: #666;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        
        &::before {
          content: '';
          width: 16px;
          height: 16px;
          background: url('/assets/coin.png') no-repeat center;
          background-size: contain;
        }
      }
    }
  }

  /* 祭品区域 */
  .offerings-area {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
	z-index: 100;
  }
  
  .offering-table {
    position: absolute;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%);
    width: 300px;
    height: 100px;
  }
  
  .table-surface {
    width: 100%;
    height: 20px;
    background: linear-gradient(to bottom, #d4d4d4, #a0a0a0);
    border-radius: 5px;
  }
  
  .incense-holder {
    position: absolute;
    top: -30px;
    left: 50%;
    transform: translateX(-50%);
    width: 40px;
    height: 40px;
    background: #8b4513;
    border-radius: 50%;
  }
  
  .incense-ash {
    position: absolute;
    top: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 20px;
    background: #dcdcdc;
    border-radius: 50%;
  }
  
  .offering-item {
    position: absolute; /* Positioned relative to memorial-area */
    cursor: move;
    user-select: none;
    /* 将transition从这里移除，避免拖动过程中的动画干扰 */
    filter: drop-shadow(0 0.3125rem 0.3125rem rgba(0, 0, 0, 0.3)); /* 5px 5px */
    pointer-events: all; /* Enable interaction */
    z-index: 1; /* 默认z-index */
    will-change: transform; /* 提示浏览器元素将被频繁改变，可提高性能 */
  }
  
  /* 分离悬停和拖动状态的样式处理 */
  .offering-item:hover:not(.dragging) {
    transform: scale(1.1) translateY(-0.3125rem); /* 5px */
    filter: drop-shadow(0 0.625rem 0.625rem rgba(0, 0, 0, 0.4)); /* 10px 10px */
    transition: transform 0.3s, filter 0.3s; /* 只在悬停时应用过渡 */
  }
  
  /* 单独设置拖动中的样式 */
  .offering-item.dragging {
    transform: scale(1.1); /* 只缩放，不上移，避免退缩感 */
    filter: drop-shadow(0 0.625rem 0.625rem rgba(0, 0, 0, 0.5)); /* 更明显的阴影 */
    /* 拖动时不应用过渡效果 */
    opacity: 0.9; /* 轻微透明提示正在拖动 */
  }
  
  .offering-item img {
    width: 3.75rem; /* 60px */
    height: 3.75rem; /* 60px */
    object-fit: contain;
    display: block; /* Prevents bottom space */
    pointer-events: none; /* 防止图片接收事件，确保事件传递给父元素 */
  }
</style>
